import uuid
from flask import Blueprint, request, jsonify
from services.chroma_service import ChromaService
from models.document import Document, Knowledge, DocumentSegment, db

segment_bp = Blueprint('segment', __name__)
chroma_service = ChromaService()

@segment_bp.route('/', methods=['GET'])
def list_records():
    # 获取分页参数
    page = int(request.args.get("page", 1))
    page_size = int(request.args.get("page_size", 10))
    
    # 获取查询参数
    search_type = request.args.get("search_type")
    record_id = request.args.get("id")
    query_text = request.args.get("query_text")
    metadata_filter = request.args.get("metadata_filter")
    document_filter = request.args.get("document_filter")
    n_results_requested = int(request.args.get("n_results", 1000))
    document_id = request.args.get('document_id')

    try:
        if not document_id:
            return jsonify({'error': 'document_id is required'}), 400

        document = Document.query.get(document_id)
        if not document:
            return jsonify({'error': 'Document not found'}), 404

        knowledge = Knowledge.query.get(document.knowledge_id)
        if not knowledge:
            return jsonify({'error': 'Knowledge not found'}), 404

        collection_name = knowledge.collection_name
        
        # Handle metadata_filter
        if metadata_filter == "{}":
            metadata_filter = {}
            
        result = chroma_service.list_records(
            collection_name=collection_name, 
            page=page, 
            page_size=page_size, 
            search_type=search_type, 
            record_id=record_id, 
            query_text=query_text, 
            metadata_filter=metadata_filter, 
            document_filter=document_filter, 
            n_results_requested=n_results_requested
        )
        return jsonify(result)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@segment_bp.route('/', methods=['POST'])
def create_record():
    try:
        data = request.get_json()
        document_id = data.get('document_id')
        if not document_id:
            return jsonify({'error': 'document_id is required'}), 400

        document = Document.query.get(document_id)
        if not document:
            return jsonify({'error': 'Document not found'}), 404

        knowledge = Knowledge.query.get(document.knowledge_id)
        if not knowledge:
            return jsonify({'error': 'Knowledge not found'}), 404

        collection_name = knowledge.collection_name
        content = data.get('content')
        metadata = data.get('metadata', {})
        
        # Generate UUID for the segment
        record_id = str(uuid.uuid4())
        
        # Save to Chroma
        result = chroma_service.create_record(collection_name, record_id, content, metadata)
        
        # Save to database
        # try:
        #     seg_id_int = int(record_id)
        #     segment = DocumentSegment(
        #         id=seg_id_int,
        #         document_id=document_id,
        #         text=content,
        #         metadata=metadata
        #     )
        #     db.session.add(segment)
        #     db.session.commit()
        # except ValueError:
        #     pass

        return jsonify(result), 201
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@segment_bp.route('/<record_id>', methods=['PUT'])
def update_record(record_id):
    try:
        data = request.get_json()
        document_id = data.get('document_id')
        if not document_id:
            return jsonify({'error': 'document_id is required'}), 400

        document = Document.query.get(document_id)
        if not document:
            return jsonify({'error': 'Document not found'}), 404

        knowledge = Knowledge.query.get(document.knowledge_id)
        if not knowledge:
            return jsonify({'error': 'Knowledge not found'}), 404

        collection_name = knowledge.collection_name
        content = data.get('content')
        metadata = data.get('metadata', {})

        result = chroma_service.update_record(collection_name, record_id, content, metadata)
        
        # Update database
        # try:
        #     seg_id_int = int(segment_id)
        #     segment = DocumentSegment.query.get(seg_id_int)
        #     if segment:
        #         segment.content = content
        #         segment.metadata = metadata
        #         db.session.commit()
        # except ValueError:
        #     pass

        return jsonify(result), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@segment_bp.route('/<record_id>', methods=['DELETE'])
def delete_record(record_id):
    try:
        document_id = request.args.get('document_id')
        if not document_id:
            return jsonify({'error': 'document_id is required'}), 400

        document = Document.query.get(document_id)
        if not document:
            return jsonify({'error': 'Document not found'}), 404

        knowledge = Knowledge.query.get(document.knowledge_id)
        if not knowledge:
            return jsonify({'error': 'Knowledge not found'}), 404

        collection_name = knowledge.collection_name
        
        result = chroma_service.delete_record(collection_name, record_id)
        
        # # 只有当 segment_id 可转换为 int 时才删除数据库中的记录
        # try:
        #     seg_id_int = int(segment_id)
        #     segment = DocumentSegment.query.get(seg_id_int)
        #     if segment:
        #         db.session.delete(segment)
        #         db.session.commit()
        # except ValueError:
        #     # 如果 segment_id 不能转换为 int，则跳过删除操作
        #     pass

        return jsonify(result), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@segment_bp.route('/batch-delete', methods=['POST'])
def batch_delete_records():
    try:
        data = request.get_json()
        document_id = data.get('document_id')
        if not document_id:
            return jsonify({'error': 'document_id is required'}), 400

        document = Document.query.get(document_id)
        if not document:
            return jsonify({'error': 'Document not found'}), 404

        knowledge = Knowledge.query.get(document.knowledge_id)
        if not knowledge:
            return jsonify({'error': 'Knowledge not found'}), 404

        collection_name = knowledge.collection_name
        record_ids = data.get('record_ids', [])

        result = chroma_service.batch_delete_records(collection_name, record_ids)
        
        # # 过滤掉 segment_ids 中不能转换为 int 的项
        # filtered_ids = []
        # for seg_id in segment_ids:
        #     try:
        #         filtered_ids.append(int(seg_id))
        #     except (ValueError, TypeError):
        #         pass

        # # Delete from database
        # DocumentSegment.query.filter(DocumentSegment.id.in_(filtered_ids)).delete(synchronize_session=False)
        # db.session.commit()

        return jsonify(result), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

